//
//  AddMapViewController.m
//  SelfDriving
//
//  Created by apple on 15/10/30.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "AddMapViewController.h"
#import "MapCell.h"
#import "ReleaseMainVC.h"
#import "XhwWebViewController.h"
@interface AddMapViewController ()<UITableViewDataSource,UITableViewDelegate,MAMapViewDelegate,AMapSearchDelegate>
@property (strong, nonatomic) UITableView *table;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *sview;
@property (weak, nonatomic) IBOutlet UITextField *stext;

@end

@implementation AddMapViewController
{
    NSMutableArray *data;
    int selectIndex;
    MAUserLocation *loc;
 }
- (IBAction)submitAction:(UIButton *)sender {
    [self.view endEditing:YES];
    _mapView.centerCoordinate = loc.location.coordinate;
    
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:loc.location.coordinate.latitude longitude:loc.location.coordinate.longitude];//中心点
    request.types =  @"风景名胜|商务住宅|政府机构及社会团体|交通设施服务|公司企业|道路附属设施|地名地址信息";
    request.sortrule = 0;
    request.requireExtension = YES;
    request.keywords = [_stext.text trim];
    //发起附近周边搜索
    [_search AMapPOIAroundSearch:request];
}
- (void)viewDidLoad {
    [SVProgressHUD showWithStatus:@"定位中..."];
    [super viewDidLoad];
//    _map.showsUserLocation = YES;
//    _map.hidden = YES;
//    _map.zoomLevel = 16;//地图显示比例
//    _map.rotateEnabled = NO; //设置是否可以旋转
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
    _search = [[AMapSearchAPI alloc]init];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
    _stext.leftView = view;
    _stext.leftViewMode = UITextFieldViewModeAlways;
    _sview.layer.cornerRadius = 13;
    self.search.delegate = self;

    
    
    self.mapView.userTrackingMode  = MAUserTrackingModeNone;
    
    CGRect r = self.mapView.frame;
    r.size.height = SCRE_HEIGHT-(SCRE_HEIGHT/3)+64;
    _mapView.frame = r;
    
    
     _table = [[UITableView alloc]initWithFrame:CGRectMake(0, SCRE_HEIGHT-(SCRE_HEIGHT/3)+64, SCRE_WIDTH,SCRE_HEIGHT/3-64)];
    
    _table.backgroundColor = UIColorFromRGB(0xeeeeee);
    _table.delegate = self;
    _table.dataSource = self;
    [self.view addSubview:_table];
}
#pragma  mark 高德
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (updatingLocation)
    {
        loc = userLocation;
        _mapView.delegate = nil;

        _mapView.centerCoordinate = userLocation.location.coordinate;
        
        AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];//中心点
        request.types =  @"风景名胜|商务住宅|政府机构及社会团体|交通设施服务|公司企业|道路附属设施|地名地址信息";
        request.sortrule = 0;
        request.requireExtension = YES;
           //发起附近周边搜索
        [_search AMapPOIAroundSearch:request];
    }
}
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"%s: searchRequest = %@, errInfo= %@", __func__, [request class], error);
}

-(void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    [SVProgressHUD dismiss];
     data = [[NSMutableArray alloc]init];
    for (AMapPOI *info in response.pois)
    {
        MAPointAnnotation *anno = [[MAPointAnnotation alloc] init];
        anno.title = [NSString stringWithFormat:@"%@(距离 %.1ld 米)", info.name, (long)info.distance];
        
        [_mapView addAnnotation:anno];
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:info.address forKey:@"address"];
        //        [dic setObject:info.city forKey:@"city"];
        [dic setObject:info.name forKey:@"name"];
        [dic setObject:[NSString stringWithFormat:@"%f",info.location.latitude] forKey:@"latitude"];
        [dic setObject:[NSString stringWithFormat:@"%f",info.location.longitude] forKey:@"longitude"];
        [data addObject:dic];
    }
    [_table reloadData];
}
//-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
//    _map.hidden = NO;
//    BMKCoordinateRegion viewRegion = BMKCoordinateRegionMake(userLocation.location.coordinate, BMKCoordinateSpanMake(0.02f,0.02f));
//    BMKCoordinateRegion adjustedRegion = [_map regionThatFits:viewRegion];
//    [_map setRegion:adjustedRegion animated:YES];
//    [_map updateLocationData:userLocation];//显示按钮
//    [locService stopUserLocationService];
//    //初始化检索对象
//    _searcher =[[BMKGeoCodeSearch alloc]init];
//    _searcher.delegate = self;
//    BMKReverseGeoCodeOption *geoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
//    geoCodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
//    BOOL flag = [_searcher reverseGeoCode:geoCodeSearchOption];
//    if(flag)
//    {
//        NSLog(@"geo检索发送成功");
//    }
//    else
//    {
//        NSLog(@"geo检索发送失败");
//    }
//    [SVProgressHUD dismiss];
//}
//-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
//    if (error == BMK_SEARCH_NO_ERROR) {
//        [SVProgressHUD dismiss];
//        data = [[NSMutableArray alloc]init];
//        for (int i = 0; i < result.poiList.count; i++)
//        {
//            BMKPoiInfo* poi = [result.poiList objectAtIndex:i];
//            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//            [dic setObject:poi.address forKey:@"address"];
//            [dic setObject:poi.city forKey:@"city"];
//            [dic setObject:poi.name forKey:@"name"];
//            [dic setObject:[NSString stringWithFormat:@"%f",poi.pt.latitude] forKey:@"latitude"];
//            [dic setObject:[NSString stringWithFormat:@"%f",poi.pt.longitude] forKey:@"longitude"];
//
//            [data addObject:dic];
//        }
//        [_table reloadData];
//    }
//    else {
//        NSLog(@"抱歉，未找到结果");
//    }
//}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return data.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MapCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"MapCell"];
    if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"MapCell" owner:nil options:nil];
        cell = [nibs lastObject];
        cell.backgroundColor = [UIColor whiteColor];
    };
    NSMutableDictionary *dic = [data objectAtIndex:indexPath.row];
    cell.detailsLabel.text = [dic objectForKey:@"address"];
    cell.addressLable.text = [dic objectForKey:@"name"];
    cell.selectedBtn.tag = indexPath.row + 1;
    if (selectIndex == indexPath.row) {
        cell.selectedBtn.selected = YES;
    }else{
        cell.selectedBtn.selected = NO;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *dic = [data objectAtIndex:indexPath.row];
    selectIndex = indexPath.row;
    [_table reloadData];
    [self.datelate selectAddress:dic];
    
    //xhw2018-3-1改
    UIViewController *ctrl = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 3];
    if ([ctrl isKindOfClass:[XhwWebViewController class]]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
    }
//    [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)backAction:(id)sender {
//    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
